package com.qf.erp_system_admin.controller;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.erp_system_admin.entity.User;
import com.qf.erp_system_admin.entity.UserVo;
import com.qf.erp_system_admin.service.UserService;
import com.qf.erp_system_admin.util.MdUnitMeasureReadListener;
import com.qf.erp_system_admin.util.R;
import com.qf.erp_system_admin.util.RsaUtils;
import com.sun.org.apache.bcel.internal.generic.RET;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * @author baishi Li
 * @date
 * @desc
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    private Logger logger = LogManager.getLogger(UserController.class);
    @Autowired
    private UserService service;
    @PostMapping("/login")
    public R login(@RequestBody User user ,HttpSession session) throws Exception {
        String pwd = RsaUtils.decryptByPrivateKey(user.getLgPassword());
        user.setLgPassword(pwd);
        boolean result = service.login(user,session);
        if (result == true){
            HashMap<String , String> map = new HashMap<>();
            map.put("token", UUID.randomUUID().toString());
            return R.ok(20000,"成功",map);
        }else {
            return R.fail();
        }
    }
    @GetMapping("/info")
    public R  getUserInfo(HttpSession session){
        User info =  service.getUserInfo(session);
        return R.ok(20000,"成功",info);
    }
    @PostMapping("/logout")
    public R  logout(HttpSession session){
        service.logout(session);
        return R.ok(20000,"成功");
    }

    @GetMapping("/findAll")
    public R  findAll(@RequestParam HashMap<String , String> map){
        int pageNum = Integer.parseInt(map.get("pageNum"));
        int pageSize = Integer.parseInt(map.get("pageSize"));
        //开始分页
        PageHelper.startPage(pageNum,pageSize);
       List<User> user = service.findAll(map);
        PageInfo<User> info = new PageInfo<>(user);
        return R.ok(20000,"成功",info);
    }
    @GetMapping("/del")
    public  R del(@RequestParam int lgId){
        int result = service.del(lgId);
        if (result > 0){
            return R.ok(20000,"成功",result);
        }else {
            return R.fail();
        }
    }
    @PostMapping("/add")
    public  R add(@RequestBody User user){
        int result = service.add(user);
        if (result > 0){
            return R.ok(20000,"成功",result);
        }else {
            return R.fail();
        }
    }
    @PostMapping("/edit")
    public  R edit(@RequestBody User user){
        int result = service.edit(user);
        if (result > 0){
            return R.ok(20000,"成功",result);
        }else {
            return R.fail();
        }
    }
    @PostMapping("/powerSelect")
    public R powerSelect(@RequestBody User user){
        System.out.println("接收到的对象："+user);
        UserVo result = service.powerSelect(user);
        return R.ok(20000,"成功",result);
    }
    @GetMapping("/decryptStr")
    public R decryptStr(@RequestParam String password){
        String result = service.decryptStr(password);
        return R.ok(20000,"成功",result);
    }
    @GetMapping("/download/excel")
    public void downloadExcel(HttpServletResponse response) throws IOException {
        //  查询数据库全部数据
        List<User> list = service.findAll(null);
        // 下面这个注释是前端使用方式1,即a标签发请求时采用
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        String fileName = URLEncoder.encode("计量单位信息", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        // easyexcel导出工具
        EasyExcel.write(response.getOutputStream(), User.class).autoCloseStream(Boolean.FALSE).sheet("所有用户信息信息")
                .doWrite(list);
    }

    @PostMapping("/upload/excel")
    public R uploadExcel(MultipartFile file) {
        try {
            // 重点,此处第三个参数需要传入Service对象
            EasyExcel.read(file.getInputStream( ),
                            User.class,
                            new MdUnitMeasureReadListener(service))
                    .sheet( ).doRead( );
        }catch (Exception e){
            e.printStackTrace();
            return R.fail();
        }
        return R.ok( );
    }
}
